//
//  File.swift
//
//
//  Created by didi on 2022/9/13.
//

import Vapor

public protocol ApiCreateController: CreateController where CreateContext: Decodable {
    func createValidators() -> [AsyncValidator]
    func createInput(_ req: Request, _ model: DatabaseModel, _ input: CreateContext) async throws
    func createApi(_ req: Request) async throws -> Response
    func createResponse(_ req: Request, _ model: DatabaseModel) async throws -> Response
    func setUpCreateRoutes(_ routes: RoutesBuilder)
}

public extension ApiCreateController {
    func createValidators() -> [AsyncValidator] { [] }

    func createApi(_ req: Request) async throws -> Response {
        let hasAccess = try await createAccess(req)
        guard hasAccess else { throw Abort(.forbidden) }

        try await RequestValidator(createValidators()).validate(req)
        let input = try req.content.decode(CreateContext.self)
        let model = DatabaseModel()
        try await createInput(req, model, input)
        try await beforeCreate(req, model, input)
        try await creating(req, model, input)
        try await afterCreate(req, model, input)
        return try await createResponse(req, model)
    }

    func setUpCreateRoutes(_ routes: RoutesBuilder) {
        let baseRouters = getBaseRoutes(routes)
        baseRouters.post(use: createApi)
    }
}
